/**
 * @author ming
 * @date 2021/2/14 21:52
 * @desc mongo 连接
 */
package mongo

import (
	"beego-template/g"
	"errors"
	"strings"
	"time"

	"github.com/astaxie/beego"
	"gopkg.in/mgo.v2"
)

// 连接mongodb数据库
var (
	mongodbAddr     = "" //mongodb 数据库地址
	mongodbName     = "" //mongodb 数据名称
	mongodbUser     = "" //mongodb 用户名
	mongodbPassword = "" //mongodb 密码
	mongoAuthDb     = "" //mongo 认证数据库
)

var (
	mongoSession *mgo.Session
)

func init() {
	mongodbAddr = beego.AppConfig.String("mongodb-addr")
	mongodbName = beego.AppConfig.String("mongodb-name")
	mongodbUser = beego.AppConfig.String("mongodb-username")
	mongodbPassword = beego.AppConfig.String("mongodb-password")
	mongoAuthDb = beego.AppConfig.String("mongo-auth-db")
}

func NewMongoSession() *mgo.Session {
	if mongoSession == nil {
		var err error

		if mongodbUser == "" || mongodbPassword == "" {
			mongoSession, err = mgo.Dial(mongodbAddr)
		} else {
			dialInfo := &mgo.DialInfo{
				Addrs:     strings.Split(mongodbAddr, ","),
				Direct:    false,
				Timeout:   time.Second * 30,
				Database:  mongodbName,
				Source:    mongoAuthDb,
				Username:  mongodbUser,
				Password:  mongodbPassword,
				PoolLimit: 4096, // Session.SetPoolLimit
			}

			mongoSession, err = mgo.DialWithInfo(dialInfo)
		}

		if err != nil {
			g.Log.Error("连接mongodb失败:%s", err.Error())
			return nil
		}
	}

	return mongoSession.Clone()
}

func WithMongoCollection(collectionName string, s func(*mgo.Collection) error) error {
	session := NewMongoSession()
	if session == nil {
		return errors.New("获取mongodb连接失败")
	}
	defer session.Close()

	c := session.DB(mongodbName).C(collectionName)
	return s(c)
}
